package com.mjk.common.ai.service;


import com.mjk.common.ai.base.ThreadContext;
import com.mjk.common.ai.cosntant.RedisKeyConstant;
import com.mjk.common.ai.entity.DrawStar;
import com.mjk.common.core.jdbc.service.plus.idbservice.BeeDBService;
import com.mjk.common.core.jdbc.service.plus.wrap.BeeQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;


@Slf4j
@Service
public class DrawStarService {
    @Autowired
    private BeeDBService beeDBService;

    public List<DrawStar> listByCurrentUser(Long maxId, int pageSize) {
        BeeQueryWrapper wrapper = new BeeQueryWrapper(DrawStar.class);
        wrapper
                .eq(DrawStar::getUserId, ThreadContext.getCurrentUserId())
                .eq(DrawStar::getIsDeleted, false)
                .it(DrawStar::getId, maxId)
                .orderBy(" id desc ")
                .setPage(0, pageSize);
        return beeDBService.findManyByWrapperWithPage(wrapper).getList();
    }

    @CacheEvict(cacheNames = RedisKeyConstant.USER_INFO, condition = "#drawId>0 && #userId>0", key = "'star:'+#drawId+':'+#userId")
    public boolean toggle(Long drawId, Long userId) {
        BeeQueryWrapper wrapper = new BeeQueryWrapper(DrawStar.class);
        DrawStar drawStar = wrapper
                .eq(DrawStar::getDrawId, drawId)
                .eq(DrawStar::getUserId, userId)
                .one();
        if (null != drawStar) {
            drawStar.setIsDeleted(!drawStar.getIsDeleted());
            wrapper = new BeeQueryWrapper(DrawStar.class);
            wrapper.eq(DrawStar::getId, drawStar.getId());
            return beeDBService.update(wrapper) > 0;
        } else {
            DrawStar newObj = new DrawStar();
            newObj.setDrawId(drawId);
            newObj.setUserId(userId);
            beeDBService.insert(newObj);
            return true;
        }
    }

    @Cacheable(cacheNames = RedisKeyConstant.USER_INFO, condition = "#drawId>0 && #userId>0", key = "'star:'+#drawId+':'+#userId")
    public boolean isStarred(Long drawId, Long userId) {
        BeeQueryWrapper wrapper = new BeeQueryWrapper(DrawStar.class);
        DrawStar drawStar = wrapper
                .eq(DrawStar::getDrawId, drawId)
                .eq(DrawStar::getUserId, userId)
                .one();
        return null != drawStar && !drawStar.getIsDeleted();
    }

}
